package com.rds.material.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rds.common.ServiceException;
import com.rds.common.api.eco.domain.RdaEco;
import com.rds.common.api.eco.domain.RdaEcoRel;
//import com.rds.common.api.workflow.IRdaWorkflowApi;
import com.rds.common.api.material.IRdaPartsRelApi;
import com.rds.common.api.material.domain.*;
import com.rds.common.core.domain.entity.Document;
import com.rds.common.core.service.DocumentService;
import com.rds.common.core.service.IDynamicService;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;

import com.rds.eco.service.IRdaEcoRelService;
import com.rds.eco.service.IRdaEcoService;
import com.rds.material.dto.*;
import com.rds.material.mapper.MaterialBillMapper;
import com.rds.material.mapper.RdaPartDynamicattributevalueMapper;
import com.rds.material.mapper.RdaPartsRelMapper;
import com.rds.material.service.*;
//import com.rds.system.common.history.HistoryRecordUtil;
import com.rds.material.utils.BeanMapUtils;
import com.rds.material.utils.WorkspaceUtils;
import com.rds.system.domain.RdaTableColumn;
import com.rds.system.domain.Sharing;
import com.rds.system.service.*;
//import com.rds.workflow.service.RdaWorkflowTempleteScopeService;

//import com.rds.workspace.service.IRdaCadfileService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;


/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-11-30
 */
@Service
public class RdaPartsRelServiceImpl implements IRdaPartsRelService, IRdaPartsRelApi
{
//    @Autowired
//    private IDocumentService documentService;

    /** 文档表名 */
    private static final String tableName = "rda_document";

    @Autowired
    private IDynamicService dynamicService;
    @Autowired
    private DocumentService documentService;

    @Autowired
    private RdaPartsRelMapper rdaPartsRelMapper;

    @Autowired
    private IRdaNameCodeService rdaNameCodeService;

    @Autowired
    private IMaterialBillService materialBillService;

    @Autowired
    private IRdaPartDynamicattributevalueService rdaPartDynamicattributevalueService;

    @Autowired
    private RdaPartDynamicattributevalueMapper rdaPartDynamicattributevalueMapper;

    @Autowired
    private IRdaPartDynamicattributeService rdaPartDynamicattributeService;

//    @Autowired
//    private RdaWorkflowTempleteScopeService rdaWorkflowTempleteScopeService;

//    @Autowired
//    private IRdaWorkflowApi rdaWorkflowTempleteScopeService;

    @Autowired
    private IRdaPartService rdaPartService;

    @Autowired
    private IRdaTypeService rdaTypeService;

    @Autowired
    private IRdaPolicyService rdaPolicyService;

    @Autowired
    private IRdaStateService rdaStateService;

    @Autowired
    private MaterialBillMapper materialBillMapper;

    @Autowired
    private ISysHistoryService sysHistoryService;
//
//    @Autowired
//    private IRdaCadfileService rdaCadfileService;

    @Autowired
    private IRdaEcoRelService rdaEcoRelService;

    @Autowired
    private IRdaEcoService rdaEcoService;


    @Autowired
    private IRdaTableColumnService rdaTableColumnService;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public RdaPartsRel selectRdaPartsRelById(Long id)
    {
        return rdaPartsRelMapper.selectRdaPartsRelById(id);
    }

    @Override
    public List<RdaPartsRel> getRelAndBill(Long id) {
        return rdaPartsRelMapper.getRelAndBill(id);
    }

    @Override
    public RdaPartsRel selectBillByRelId(Long id){
        return rdaPartsRelMapper.selectBillByRelId(id);
    }

    @Override
    public int addFile(Sharing rdaMemberlistUser) {
//        Long dId = rdaMemberlistUser.getPmsid();
//        List<RdaCadfile> fileList=rdaMemberlistUser.getFileList();
//        if(fileList==null){
//             throw new ServiceException("请选择需要上传的文件");
//        }
//        RdaCadfile rdaCadfile=new RdaCadfile();
//        rdaCadfile.setObjectid(dId);
//        rdaCadfile.setStatus(1L);
//        List<RdaCadfile> listFile=rdaCadfileService.selectRdaCadfileList(rdaCadfile);
//        int count=0;
//        int count1=0;
//        if(listFile.size()!=0){
//            count=Integer.parseInt(listFile.get(listFile.size()-1).getRevision());//获取当前最大版本号
//        }
//        int rows = 0;
//        String username = SecurityUtils.getUsername();
//        for(RdaCadfile file:fileList){
//            String suffix= WorkspaceUtils.getFileSuffix(file.getFileName(),"2");
//            count++;
//            rdaCadfile.setFileName(file.getFileName());
//            int num=rdaCadfileService.selectRdaCadfileList(rdaCadfile).size();
//            if(num>0){
//                count1++;
//            }else{
//                file.setMasterid(SnowFlakeUtils.nextId());
//                file.setId(SnowFlakeUtils.nextId());
//                file.setObjectid(dId);
//                file.setFileSize(""+Integer.parseInt(file.getFileSize()));
//                file.setUserName(username);
//                file.setCreateTime(DateUtils.getNowDate());
//                file.setFormat(suffix);
//                rows=rdaCadfileService.insertRdaCadfile(file);
//                //通过rel关系表找到materialbill
//                RdaPartsRel rdaPartsRel = selectBillByRelId(dId);
//                MaterialBill materialBill = materialBillMapper.selectMaterialBillById(rdaPartsRel.getFromid());
////                new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(dId,"添加附件",materialBill.getStateid(),"物料零件",file.getFileName());
//            }
//        }
//        if(count1>0){
//            if(rows>0){
//                throw new ServiceException("操作成功，"+count1+"个文件已存在，请用更新文件操作！");
//            }else{
//                throw new ServiceException(("操作失败，已存在同文件名文件"));
//            }
//        }
//        return rows;
        return 0;
    }

    @Override
    public void copywbs(List<Sharing> sharing) {
        for (Sharing sharingP : sharing) {
            //复制
            RdaPartsRel rdaPartsRelF = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(sharingP.getFromid()));
            RdaPartsRel rdaPartsRelT = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(sharingP.getToid()));
            if (1==sharingP.getType()){
                RdaPartsRel rdaPartsRel = new RdaPartsRel();
                BeanUtils.copyProperties(rdaPartsRelF,rdaPartsRel);
                long id = SnowFlakeUtils.nextId();
                rdaPartsRel.setId(id);
                rdaPartsRel.setCreateTime(DateUtils.getNowDate());
                rdaPartsRel.setParentId(rdaPartsRelT.getId());
                rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRel);
                updateorderforupdate(rdaPartsRelT.getId(),0L,"");
            }
            //剪切
            else {
                //记录父id，方便调整标识
                Long parentIdF = rdaPartsRelF.getParentId();
                rdaPartsRelF.setParentId(rdaPartsRelT.getId());
                rdaPartsRelF.setUpdateTime(DateUtils.getNowDate());
                rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRelF);
                updateorderforupdate(rdaPartsRelT.getId(),0L,"");
                updateorderforupdate(parentIdF,0L,"");
            }
        }
    }

    @Override
    public void removeEbom(Long[] ids) {
        for (Long id : ids) {
            RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(id);
            rdaPartsRelMapper.deleteRdaPartsRelById(id);
            updateorderforupdate(rdaPartsRel.getParentId(),0L,"");
        }

    }

    @Override
    public void delectEbom(Long[] ids) {
        for (Long id : ids) {
            RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(id);
            rdaPartsRelMapper.deleteRdaPartsRelById(id);
            materialBillMapper.deleteMaterialBillById(rdaPartsRel.getFromid());
            updateorderforupdate(rdaPartsRel.getParentId(),0L,"");
        }
    }

    @Override
    /**
     *ids:对应rda_material_bill的id
     * toid\pmsid:对应rda_parts_bill的id
     * projectid:对应页面根节点rda_parts_bill的id
     */
    public void InsertExistAsChild(Sharing rdaPmsassignRel) {
        String ids = rdaPmsassignRel.getIds();
        String[] split = ids.split(",");
        //选中根节点是pmsid和toid为0，需要拿projectid
        RdaPartsRel rdaPartsRel;
        if ("0".equals(rdaPmsassignRel.getPmsid())){
            rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(rdaPmsassignRel.getProjectid());
        }else {
            rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(rdaPmsassignRel.getPmsid()));
        }
        //勾选多个
        for (String s : split) {
            MaterialBill materialBill = materialBillMapper.selectMaterialBillById(Long.parseLong(s));
            RdaPartsRel rdaPartsRelN = new RdaPartsRel();
            BeanUtils.copyProperties(rdaPartsRel,rdaPartsRelN);
            rdaPartsRelN.setId(SnowFlakeUtils.nextId());
            rdaPartsRelN.setFromid(materialBill.getId());
            rdaPartsRelN.setFromtype(materialBill.getTypeid());
            rdaPartsRelN.setParentId(rdaPartsRel.getId());
            rdaPartsRelN.setLevel(rdaPartsRel.getLevel()+1);
            rdaPartsRelN.setRelName("Classfited Item");
            rdaPartsRelN.setCreateTime(DateUtils.getNowDate());
            rdaPartsRelN.setUpdateTime(DateUtils.getNowDate());
            rdaPartsRelN.setRemark(materialBill.getDescription());
            rdaPartsRelN.setQuantity(null);
            rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRelN);
            updateorderforupdate(rdaPartsRel.getId(),0L,"");
        }
    }

    /**
     *ids:对应rda_material_bill的id
     * toid\pmsid:对应rda_parts_bill的id
     * projectid:对应页面根节点da_parts_bill的id
     */
    @Override
    public void InsertExistAsLevel(Sharing rdaPmsassignRel) {
        String ids = rdaPmsassignRel.getIds();
        String[] split = ids.split(",");
        RdaPartsRel rdaPartsRel;
        if ("0".equals(rdaPmsassignRel.getPmsid())){
            rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(rdaPmsassignRel.getProjectid());
        }else {
            rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(rdaPmsassignRel.getPmsid()));
        }
        for (String s : split) {
            MaterialBill materialBill = materialBillMapper.selectMaterialBillById(Long.parseLong(s));
            RdaPartsRel rdaPartsRelN = new RdaPartsRel();
            BeanUtils.copyProperties(rdaPartsRel,rdaPartsRelN);
            rdaPartsRelN.setId(SnowFlakeUtils.nextId());
            rdaPartsRelN.setFromid(materialBill.getId());
            rdaPartsRelN.setFromtype(materialBill.getTypeid());
            rdaPartsRelN.setParentId(rdaPartsRel.getParentId());
            rdaPartsRelN.setRelName("Classfited Item");
            rdaPartsRelN.setCreateTime(DateUtils.getNowDate());
            rdaPartsRelN.setUpdateTime(DateUtils.getNowDate());
            rdaPartsRelN.setRemark(materialBill.getDescription());
            rdaPartsRelN.setQuantity(null);
            rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRelN);
            updateorderforupdate(rdaPartsRel.getParentId(),0L,"");
        }
    }

    /**
     *ids:对应rda_material_bill的id
     * toid\pmsid:对应rda_parts_bill的id
     * projectid:对应页面根节点da_parts_bill的id
     */
    @Override
    public void InsertExistAsUpper(Sharing rdaPmsassignRel) {
        String ids = rdaPmsassignRel.getIds();
        String[] split = ids.split(",");
        RdaPartsRel rdaPartsRel;
        if ("0".equals(rdaPmsassignRel.getPmsid())){
            rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(rdaPmsassignRel.getProjectid());
        }else {
            rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(rdaPmsassignRel.getPmsid()));
        }
        Long parentId = rdaPartsRel.getParentId();
        for (String s : split) {
            MaterialBill materialBill = materialBillMapper.selectMaterialBillById(Long.parseLong(s));
            RdaPartsRel rdaPartsRelN = new RdaPartsRel();
            BeanUtils.copyProperties(rdaPartsRel,rdaPartsRelN);
            rdaPartsRelN.setId(SnowFlakeUtils.nextId());
            rdaPartsRelN.setFromid(materialBill.getId());
            rdaPartsRelN.setFromtype(materialBill.getTypeid());
            rdaPartsRelN.setParentId(rdaPartsRel.getParentId());
            rdaPartsRelN.setRelName("Classfited Item");
            rdaPartsRelN.setCreateTime(DateUtils.getNowDate());
            rdaPartsRelN.setUpdateTime(DateUtils.getNowDate());
            rdaPartsRelN.setRemark(materialBill.getDescription());
            rdaPartsRelN.setQuantity(null);
            rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRelN);
            updateorderforupdate(parentId,0L,"");

            rdaPartsRel.setLevel(rdaPartsRelN.getLevel()+1);
            rdaPartsRel.setParentId(rdaPartsRelN.getId());
            rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRel);
            updateorderforupdate(rdaPartsRel.getParentId(),0L,"");

        }
    }

    @Override
    public void bindDoc(Sharing rdaPmsassignRel) {
        String ids = rdaPmsassignRel.getIds();
        String[] split = ids.split(",");
        Long pmsid = Long.parseLong(rdaPmsassignRel.getPmsid());
        RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(pmsid);
        for (String s : split) {
//            Document document = documentService.selectDocumentById(Long.parseLong(s));
//            List<HashMap<String,Object>> docList= dynamicService.selectListByIds(tableName,ids);
            HashMap<String, Object> stringObjectHashMap = dynamicService.selectDataById(tableName, Long.parseLong(s));
            Long id = (Long) stringObjectHashMap.get("id");
            Integer typeid = (Integer) stringObjectHashMap.get("typeid");

            RdaPartsRel rdaPartsRel1 = new RdaPartsRel();
            rdaPartsRel1.setId(SnowFlakeUtils.nextId());
            rdaPartsRel1.setFromid(rdaPartsRel.getFromid());
            rdaPartsRel1.setFromtype(rdaPartsRel.getFromtype());
            rdaPartsRel1.setRelName("doc");
            rdaPartsRel1.setToid(id);
            rdaPartsRel1.setTotype(typeid);
            rdaPartsRel1.setCreateTime(DateUtils.getNowDate());
            rdaPartsRel1.setUpdateTime(DateUtils.getNowDate());
            rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRel1);
        }
    }


    @Override
    public JSONObject RelAndBillList(ServletRequest request) {
        JSONObject jsonobj = new JSONObject();
        ArrayList<String> jsonList=new ArrayList<String>();
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String projectid=httpRequest.getParameter("projectid");

        List<RdaPartsRel> relAndBill = rdaPartsRelMapper.getRelAndBill(Long.parseLong(projectid));

        //获取这个模块的所有状态
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("EC Part","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Object> dstateMap=(Map)dmap.get("Stateid");
        String stateid = dstateMap.get("Obsolete").toString();
        relAndBill.forEach(m->{
            //如果为废弃状态则过滤
//            if (stateid.equals(m.getMaterialBill().getStateid().toString())){
//                return;
//            }
            StringBuilder json=new StringBuilder();
            //返回前端渲染对象
            MaterialBillAndRdaPartsRel materialBillAndRdaPartsRel = new MaterialBillAndRdaPartsRel(m);
            String stringJSON = JSON.toJSONString(materialBillAndRdaPartsRel);
            json.append(stringJSON);
            RdaPartDynamicattributevalue rdaPartDynamicattributevalue=new RdaPartDynamicattributevalue();
            rdaPartDynamicattributevalue.setObjectid(m.getId());
            List<RdaPartDynamicattributevalue> rdaPartDynamicattributevalueList=rdaPartDynamicattributevalueService.selectRdaPartDynamicattributevalueList(rdaPartDynamicattributevalue);
            String attribute = "";
            for(RdaPartDynamicattributevalue partDynamicattributevalue:rdaPartDynamicattributevalueList){
                String value;
                if (partDynamicattributevalue.getAttributeValue() == null ||
                        partDynamicattributevalue.getAttributeValue().equals("null")) {
                    value = "";
                }
                else {
                    value=partDynamicattributevalue.getAttributeValue();
                }
                attribute += ",\""+partDynamicattributevalue.getAttributeName()+"\":\""+value+"\"";//字符串两边含有双引号
            }
            if(attribute!=null && attribute.length()>0){
                json.insert(json.length()-1,attribute);
            }
            jsonList.add(json.toString());
        });
        String jarr = JSON.toJSONString(jsonList);
        JSONArray jsonArray = JSONArray.parseArray(jarr);
        List<Object> list = JSON.parseArray(jsonArray.toJSONString(), Object.class);
        List<JSONObject> result = new ArrayList<>();
        for (Object obj : list) {
            JSONObject jsonObject = JSON.parseObject(obj.toString());
            result.add(jsonObject);
        }
        jsonobj.put("rows", result);
        jsonobj.put("total", relAndBill.size());
        return jsonobj;
    }

    @Override
    public int addMaterialAddRel(Map<String, Object> map,String type) {
        //物料表
        MaterialBill materialBill = new MaterialBill();
        materialBill.setId(SnowFlakeUtils.nextId());
        //物料关系表
        RdaPartsRel rdaPartsRel = new RdaPartsRel();
        rdaPartsRel.setId(SnowFlakeUtils.nextId()+1L);

        //分类属性键
        ArrayList<String> attribute_key=new ArrayList<String>();//临时存储json键
        //分类属性值
        ArrayList<String> attribute_value=new ArrayList<String>();//临时存储json值
        HashMap<String, String> attribute = new HashMap<>();

        //将json转换成map循环取键值对
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if(entry.getKey().equals("code")){
                String attributeValue=(String)entry.getValue();
                materialBill.setCode(attributeValue);
            }else if(entry.getKey().equals("name")){
                String attributeValue=(String)entry.getValue();
                materialBill.setName(attributeValue);
            }else if(entry.getKey().equals("remark")){
                String attributeValue=(String)entry.getValue();
                materialBill.setDescription(attributeValue);
                rdaPartsRel.setRemark(attributeValue);
            }else if(entry.getKey().equals("ownerid")){
//                String attributeValue=(String)entry.getValue();
                String attributeValue=Integer.toString((Integer)entry.getValue());
                materialBill.setOwnerid(Integer.parseInt(attributeValue));
            }else if(entry.getKey().equals("parentid")){
                Long attributeValue=(Long)entry.getValue();
                rdaPartsRel.setParentId(attributeValue);
                rdaPartsRel.setToid(attributeValue);
                materialBill.setParentid(attributeValue);
            }else if(entry.getKey().equals("projectid")){
                Object value = entry.getValue();
                String attributeValue = value.toString();
//                rdaPartsRel.setQuantity(Long.parseLong(attributeValue));
            }
            else if(entry.getKey().equals("stateid")){
                Long stateid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= stateid;
                materialBill.setStateid(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("typeid")){
                Long typeid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= typeid;
                materialBill.setTypeid(Math.toIntExact(attributeValue));
                rdaPartsRel.setFromtype(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("policyid")){
                Long policyid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= policyid;
                materialBill.setPolicyid(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("quantity")){
                String value = entry.getValue().toString();
                Double number = Double.parseDouble(value==null?"0":value);
                rdaPartsRel.setQuantity(number.longValue());
            }else if(entry.getKey().equals("units")){
                String attributeValue=(String)entry.getValue();
                materialBill.setUnits(attributeValue);
            }else if(entry.getKey().equals("nametype")){
                String attributeValue=(String)entry.getValue();
                materialBill.setNametype(attributeValue);
            }
            else{
                String attributeValue=String.valueOf(entry.getValue());
                attribute.put(entry.getKey(),attributeValue);
                attribute_key.add(entry.getKey());
                attribute_value.add(attributeValue);
            }
        }

        //自动编码
        if (materialBill.getCode() == null) {
            if (materialBill.getNametype()!=null){
                materialBill.setCode(materialBill.getNametype().concat(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()), "")));
            }else {
                materialBill.setCode(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()),""));
            }
        }

        //查找是否有动态属性
        RdaPartDynamicattribute rdaPartDynamicattribute = new RdaPartDynamicattribute();
        rdaPartDynamicattribute.setTypeid(materialBill.getParentid());
        List<RdaPartDynamicattribute> rdaPartDynamicattributes = rdaPartDynamicattributeService.selectRdaPartDynamicattributeList(rdaPartDynamicattribute);
        for (RdaPartDynamicattribute partDynamicattribute : rdaPartDynamicattributes) {
            RdaPartDynamicattributevalue rdaPartDynamicattributevalue=new RdaPartDynamicattributevalue();
            rdaPartDynamicattributevalue.setId(SnowFlakeUtils.nextId());
            rdaPartDynamicattributevalue.setOwnerid(SecurityUtils.getUserId());
            rdaPartDynamicattributevalue.setCreateTime(DateUtils.getNowDate());
            rdaPartDynamicattributevalue.setDynamicattributeid(partDynamicattribute.getId());
            rdaPartDynamicattributevalue.setObjectid(rdaPartsRel.getId());
            String attributeName = partDynamicattribute.getAttributeName();
            rdaPartDynamicattributevalue.setAttributeValue(attribute.get(attributeName));
            rdaPartDynamicattributevalueService.insertRdaPartDynamicattributevalue(rdaPartDynamicattributevalue);
        }

        //添加版本规则
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("EC Part","1",rdaTypeService,rdaPolicyService,rdaStateService);
        String revision=dmap.get("revision").toString();
        materialBill.setLevel(0);
        materialBill.setOwnerid(Integer.parseInt(SecurityUtils.getUserId().toString()));
        materialBill.setRevision(revision);
        rdaPartsRel.setRelName("subclass");
        rdaPartsRel.setFromid(materialBill.getId());

        RdaPart rdaPart = rdaPartService.selectRdaPartByid(materialBill.getParentid());
        if (rdaPart==null){
            rdaPartsRel.setTotype(materialBill.getTypeid().intValue());
        }else {
            rdaPartsRel.setTotype(rdaPart.getTypeid().intValue());
        }

        rdaPartsRel.setFindnumber("0");
        rdaPartsRel.setLevel(0L);
        rdaPartsRel.setCreateTime(DateUtils.getNowDate());
        rdaPartsRel.setUpdateTime(DateUtils.getNowDate());

        //添加流程
//        rdaWorkflowTempleteScopeService.createWorkflowWithObject(materialBill.getTypeid().longValue(),materialBill.getPolicyid().longValue(),materialBill.getStateid().longValue(),rdaPartsRel.getId(),"part",materialBill.getName());


        MaterialBill materialBillC = new MaterialBill();
//        materialBillC.setName(materialBill.getName());
        materialBillC.setCode(materialBill.getCode());
//        materialBillC.setRevision(materialBill.getRevision());
        //相同物料不给添加
        List<MaterialBill> materialBillList = materialBillService.selectMaterialBillList(materialBillC);
        if (materialBillList.size()>0){
            throw new ServiceException("存在编码相同的物料");

        }
//        new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(rdaPartsRel.getId(),"创建",materialBill.getStateid(),"物料零件","");

        int result = materialBillMapper.insertMaterialBill(materialBill);

        //添加下层
        if (type.equals("down")){
            //ParentId是选中的id
            RdaPartsRel rdaPartsRel1 = rdaPartsRelMapper.selectBillByRelId(rdaPartsRel.getParentId());
            rdaPartsRel.setToid(rdaPartsRel1.getToid());
            rdaPartsRel.setLevel(rdaPartsRel1.getLevel()+1);
            rdaPartsRel.setRelName("Classfited Item");
            rdaPartsRel.setTotype(materialBill.getTypeid().intValue());
            rdaPartsRel.setParentId(rdaPartsRel1.getId());
            rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRel);
            updateorderforupdate(rdaPartsRel.getParentId(),null,"");
        }else if(type.equals("addSuperior")){
            //添加上层
            //ParentId是选中的id
            RdaPartsRel rdaPartsRel1 = rdaPartsRelMapper.selectBillByRelId(rdaPartsRel.getParentId());
            if (rdaPartsRel1.getParentId().equals(rdaPartsRel1.getToid())&&rdaPartsRel1.getRelName().equals("subclass")){
                throw new ServiceException("不能选中根节点");
            }
            rdaPartsRel.setToid(rdaPartsRel1.getToid());
            rdaPartsRel.setLevel(rdaPartsRel1.getLevel());
            rdaPartsRel.setRelName("Classfited Item");
            rdaPartsRel.setTotype(materialBill.getTypeid().intValue());
            rdaPartsRel.setParentId(rdaPartsRel1.getParentId());
            rdaPartsRel.setFindnumber(rdaPartsRel1.getFindnumber());
            rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRel);
            rdaPartsRel1.setParentId(rdaPartsRel.getId());
            rdaPartsRel1.setLevel(rdaPartsRel.getLevel()+1);
            rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRel1);
            updateorderforupdate(rdaPartsRel1.getParentId(),null,"");
        }else if(type.equals("replacewithNewMaterialBill")){
            String id = map.get("id").toString();
            String restraintype = (String) map.get("restraintype");
            if ("1".equals(restraintype)){
                List<RdaPartsRel> rdaPartsRels = rdaPartsRelMapper.treeByRdaPartsRels(Long.parseLong(id));
                for (RdaPartsRel partsRel : rdaPartsRels) {
                    rdaPartsRelMapper.deleteRdaPartsRelById(partsRel.getId());
                }
                RdaPartsRel rdaPartsRel1 = rdaPartsRelMapper.selectBillByRelId(rdaPartsRel.getParentId());
                rdaPartsRel.setToid(rdaPartsRel1.getToid());
                rdaPartsRel.setLevel(rdaPartsRel1.getLevel()+1);
                rdaPartsRel.setRelName("Classfited Item");
                rdaPartsRel.setTotype(materialBill.getTypeid().intValue());
                rdaPartsRel.setParentId(rdaPartsRel1.getId());
                rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRel);
                updateorderforupdate(rdaPartsRel.getParentId(),null,"");
            }else {
                List<RdaPartsRel> rdaPartsRels = rdaPartsRelMapper.treeByRdaPartsRels(Long.parseLong(id));
                RdaPartsRel rdaPartsRel1 = rdaPartsRelMapper.selectBillByRelId(rdaPartsRel.getParentId());
                rdaPartsRel.setId(rdaPartsRels.get(0).getId());
                rdaPartsRel.setToid(rdaPartsRel1.getToid());
                rdaPartsRel.setLevel(rdaPartsRel1.getLevel()+1);
                rdaPartsRel.setRelName("Classfited Item");
                rdaPartsRel.setTotype(materialBill.getTypeid().intValue());
                rdaPartsRel.setParentId(rdaPartsRel1.getId());
                rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRel);
                updateorderforupdate(rdaPartsRel.getParentId(),null,"");
            }

        }
        //添加系列和物料的关系
        else {
            rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRel);
        }

        return result;
    }

    @Override
    public int updateMaterialAddRel(Map<String, Object> map){
        MaterialBill materialBill = new MaterialBill();
        RdaPartsRel rdaPartsRel = new RdaPartsRel();
        List<RdaPartDynamicattribute> dynamics = rdaPartDynamicattributeService.selectRdaPartDynamicattributeByTypeId(Long.parseLong(map.get("parentid").toString()));
        Map<String, Long> collect = dynamics.stream()
                .collect(Collectors.toMap(
                        RdaPartDynamicattribute::getAttributeName,  // 作为键的属性
                        RdaPartDynamicattribute::getId   // 作为值的属性
                ));
        //动态属性
        HashMap<String, String> attribute = new HashMap<>();
        //将json转换成map循环取键值对
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if(entry.getKey().equals("mid")){
                materialBill.setId(Long.parseLong(entry.getValue().toString()));
            }
            else if(entry.getKey().equals("id")){
                rdaPartsRel.setId(Long.parseLong(entry.getValue().toString()));
            }
            else if(entry.getKey().equals("code")){
                String attributeValue=(String)entry.getValue();
                materialBill.setCode(attributeValue);
            }else if(entry.getKey().equals("name")){
                String attributeValue=(String)entry.getValue();
                materialBill.setName(attributeValue);
            }else if(entry.getKey().equals("remark")){
                String attributeValue=(String)entry.getValue();
                materialBill.setDescription(attributeValue);
                rdaPartsRel.setRemark(attributeValue);
            }else if(entry.getKey().equals("ownerid")){
                materialBill.setOwnerid(Integer.parseInt(entry.getValue().toString()));
            }else if(entry.getKey().equals("parentid")){
                Long attributeValue=(Long)entry.getValue();
                rdaPartsRel.setParentId(attributeValue);
                rdaPartsRel.setToid(attributeValue);
                materialBill.setParentid(attributeValue);
            }else if(entry.getKey().equals("projectid")){
                Long projectid=(Long)entry.getValue();
                Long attributeValue= projectid;
                materialBill.setProjectid(attributeValue);
            }
            else if(entry.getKey().equals("stateid")){
                Long stateid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= stateid;
                materialBill.setStateid(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("typeid")){
                Long typeid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= typeid;
                materialBill.setTypeid(Math.toIntExact(attributeValue));
                rdaPartsRel.setFromtype(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("policyid")){
                Long policyid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= policyid;
                materialBill.setPolicyid(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("quantity")){
                Object value = entry.getValue();
                if (value instanceof Integer) {
                    Integer intValue = (Integer) value;
                    rdaPartsRel.setQuantity(intValue.longValue());
                } else if (value instanceof String) {
                    String attributeValue = value.toString();
                    rdaPartsRel.setQuantity(Long.parseLong(attributeValue));
                }
            }else if(entry.getKey().equals("units")){
                String attributeValue=(String)entry.getValue();
                materialBill.setUnits(attributeValue);
            }else if(entry.getKey().equals("nametype")){
                String attributeValue=(String)entry.getValue();
                materialBill.setNametype(attributeValue);
            }
            else if(collect.containsKey(entry.getKey())){
                String attributeValue=(String)entry.getValue();
                attribute.put(collect.get(entry.getKey())+"-"+entry.getKey(),attributeValue);
            }
        }

        //自动编码
        if (materialBill.getNametype()!=null){
            materialBill.setCode(materialBill.getNametype().concat(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()), "")));
        }

        rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRel);
        materialBillService.updateMaterialBill(materialBill);
        for (Map.Entry<String, String> m : attribute.entrySet()) {
            String key = m.getKey();
            String[] split = key.split("-");
            //先查，后改
            RdaPartDynamicattributevalue rdaPartDynamicattributevalue = rdaPartDynamicattributevalueMapper.selectRdaPartDynamicattributevalueByOidAndDid(rdaPartsRel.getId(), Long.parseLong(split[0]));
            //存在动态属性是后来才加的情况，所以在rdaPartDynamicattributevalue中还没有记录
            if (rdaPartDynamicattributevalue==null){
                RdaPartDynamicattributevalue rdaPartDynamicattributevalue1 = new RdaPartDynamicattributevalue();
                rdaPartDynamicattributevalue1.setId(SnowFlakeUtils.nextId());
                rdaPartDynamicattributevalue1.setOwnerid(SecurityUtils.getUserId());
                rdaPartDynamicattributevalue1.setCreateTime(DateUtils.getNowDate());
                rdaPartDynamicattributevalue1.setDynamicattributeid(Long.parseLong(split[0]));
                rdaPartDynamicattributevalue1.setObjectid(rdaPartsRel.getId());
                rdaPartDynamicattributevalue1.setAttributeValue(m.getValue());
                rdaPartDynamicattributevalueService.insertRdaPartDynamicattributevalue(rdaPartDynamicattributevalue1);
            }else {
                rdaPartDynamicattributevalue.setAttributeValue(m.getValue());
                rdaPartDynamicattributevalue.setModifyTime(DateUtils.getNowDate());
                rdaPartDynamicattributevalueMapper.updateRdaPartDynamicattributevalue(rdaPartDynamicattributevalue);
            }

        }
        return 1;
    }

    @Override
    public List <RdaPartsRel> billofMaterial(RdaPartsRel rdaPartsRel){
        return rdaPartsRelMapper.billofMaterial(rdaPartsRel);
    }

    @Override
    public List<MaterialBill> materialVersion(Long id) {
        //在关系中拿到具体物料的id
        RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(id);
        Long fromid = rdaPartsRel.getFromid();
        //查找具体物料
        MaterialBill materialBill = materialBillService.selectMaterialBillById(fromid);

        //查询相同物料
        MaterialBill materialBill1 = new MaterialBill();
        materialBill1.setCode(materialBill.getCode());
        materialBill1.setName(materialBill.getName());

//        List<MaterialBill> materialBillList = materialBillService.selectMaterialBillList(materialBill1);
        List<MaterialBill> materialBillList = materialBillMapper.selectMaterialBillListReplaceRelId(materialBill1);


        return materialBillList;
    }

    @Override
    public void Upgrade(MaterialVersionUpgradeDto materialVersionUpgradeDto) {
        //条件：是否保留结构
        materialVersionUpgradeDto.getUpgradewith();
        materialVersionUpgradeDto.getPmsid();
        materialVersionUpgradeDto.getProjectid();
        //查找关系，得到物料id
        RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(materialVersionUpgradeDto.getPmsid()));
        //查找物料
        MaterialBill materialBill = materialBillService.selectMaterialBillById(rdaPartsRel.getFromid());
        //判断是否是发布状态
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("EC Part","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Object> dstateMap=(Map)dmap.get("Stateid");
        String stateidc = dstateMap.get("Preliminary").toString();
        String stateidF = dstateMap.get("Obsolete").toString();
        String stateid = dstateMap.get("Release").toString();
        String stateid1 = materialBill.getStateid().toString();
        if (!stateid.equals(stateid1)) {
            throw new ServiceException("该物料不属于发布状态");
        }

        //替换关系id为新版本的物料，旧版本的物料id重新生成
        MaterialBill materialBillX = new MaterialBill();
        //materialBillX，materialBill旧版本
        BeanUtils.copyProperties(materialBill,materialBillX);
        long snowId = SnowFlakeUtils.nextId();
        materialBillX.setId(snowId);
        materialBillX.setStateid(Integer.parseInt(stateidc));
        materialBillX.setUpdateTime(DateUtils.getNowDate());
        String currentRevision  = materialBill.getRevision();
        char newRevision = currentRevision.charAt(0);
        if (Character.isDigit(newRevision)) {
            newRevision++;
        } else if (Character.isLetter(newRevision)) {
            newRevision = (char) (newRevision + 1);
        }
        materialBillX.setRevision(String.valueOf(newRevision));

        materialBill.setStateid(Integer.parseInt(stateidF));
        materialBillService.updateMaterialBill(materialBill);
        materialBillMapper.insertMaterialBill(materialBillX);


        //保留旧版本文档
        RdaPartsRel rdaPartsRelDoc = new RdaPartsRel();
        rdaPartsRelDoc.setFromid(materialBill.getId());
        rdaPartsRelDoc.setRelName("doc");
        List<RdaPartsRel> rdaPartsRels1 = rdaPartsRelMapper.selectRdaPartsRelList(rdaPartsRelDoc);
        for (RdaPartsRel partsRel : rdaPartsRels1) {
            partsRel.setId(SnowFlakeUtils.nextId());
            partsRel.setFromid(materialBillX.getId());
            rdaPartsRelMapper.insertRdaPartsRel(partsRel);
        }


        if ("0".equals(materialVersionUpgradeDto.getUpgradewith())){
            //保留旧版本ebom
            List<RdaPartsRel> rdaPartsRels = rdaPartsRelMapper.treeByRdaPartsRels(Long.parseLong(materialVersionUpgradeDto.getPmsid()));
            //记录id的映射
            HashMap<Long, Long> longLongHashMap = new HashMap<>();
            //复制旧版本的关系
            for (RdaPartsRel partsRel : rdaPartsRels) {
                long id = SnowFlakeUtils.nextId();
                if (partsRel.getId().toString().equals(materialVersionUpgradeDto.getPmsid().toString())){
                    longLongHashMap.put(partsRel.getId(),id);
                    partsRel.setId(id);
                    partsRel.setFromid(materialBillX.getId());
//                    rdaWorkflowTempleteScopeService.createWorkflowWithObject(materialBillX.getTypeid().longValue(),materialBillX.getPolicyid().longValue(),materialBillX.getStateid().longValue(),id,"part",materialBill.getName());
                }else {
                    longLongHashMap.put(partsRel.getId(),id);
                    partsRel.setId(id);
                    partsRel.setParentId(longLongHashMap.get(partsRel.getParentId()));
                }
                partsRel.setCreateTime(DateUtils.getNowDate());
                rdaPartsRelMapper.insertRdaPartsRel(partsRel);
            }
            RdaPartsRel rdaPartsRel1 = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(materialVersionUpgradeDto.getPmsid()));
            rdaPartsRel1.setParentId(0L);
            rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRel1);

        }

    }

    /**
     *
     * @param id ebom是根据id维护，拿到id可以快速定位到关系信息
     * @param type：0是EBOM结构，1是单层结构
     * @param name：物料名称
     * @param revision：物料版本
     * @return
     */
    @Override
    public List<MaterialBillAndRdaPartsRel> compareReport(Long id, String type,String name,String revision) {
        ArrayList<MaterialBillAndRdaPartsRel> list = new ArrayList<>();
        // TODO: 2024/2/22 20240222版本修改
        //单个层
        if ("1".equals(type)){
            RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(id);
            MaterialBillAndRdaPartsRel materialBillAndRdaPartsRel = new MaterialBillAndRdaPartsRel(rdaPartsRel);
            list.add(materialBillAndRdaPartsRel);
            return list;
        }
        //EBOM结构
        else {
            RdaPartsRel rdaPartsRel = new RdaPartsRel();
            rdaPartsRel.setId(id);
            List<RdaPartsRel> rdaPartsRels = rdaPartsRelMapper.billofMaterial(rdaPartsRel);
            for (RdaPartsRel partsRel : rdaPartsRels) {
                list.add(new MaterialBillAndRdaPartsRel(partsRel));
            }
            return list;
        }

    }

    @Override
    public List<MaterialBill> selectMaterialBillList(MaterialBill materialBill) {
        List<MaterialBill> materialBillList = materialBillMapper.selectMaterialBillList(materialBill);
        return materialBillList;
    }

    public List <RdaPartsRel> billofMaterialEbomLevel(RdaPartsRel rdaPartsRel){
        return rdaPartsRelMapper.billofMaterialEbomLevel(rdaPartsRel);
    }

    @Override
    public List<MaterialBillAndRdaPartsRel> referrer(Long id) {
        ArrayList<MaterialBillAndRdaPartsRel> list = new ArrayList<>();
        RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(id);
        if (rdaPartsRel.getParentId()==0||"subclass".equals(rdaPartsRel.getRelName().toString())){
//            显示上级系列，先不添加
            RdaPart rdaPart = rdaPartService.selectRdaPartByid(rdaPartsRel.getParentId());
            //废弃物料没有上级引用者
            if (rdaPart==null){
                return list;
            }
            MaterialBillAndRdaPartsRel materialBillAndRdaPartsRel = new MaterialBillAndRdaPartsRel();
            BeanUtils.copyProperties(rdaPart,materialBillAndRdaPartsRel);
            materialBillAndRdaPartsRel.setTypeid(Integer.parseInt(rdaPart.getTypeid().toString()));
            materialBillAndRdaPartsRel.setStateid(Integer.parseInt(rdaPart.getStateid().toString()));
            materialBillAndRdaPartsRel.setPolicyid(Integer.parseInt(rdaPart.getPolicyid().toString()));

            //跳转页面,是否放回上一级
            List<RdaTableColumn> tableColumn = rdaTableColumnService.selectByConfigName("material");
            Boolean previousLevel=false;
            String pageParams = "";
            String url = "";
            RdaPart rdaPart1 = rdaPartService.selectRdaPartByid(rdaPart.getProjectid());
            for (RdaTableColumn rdaTableColumn : tableColumn) {
                if ("link".equals(rdaTableColumn.getPropType())){
                    pageParams = rdaTableColumn.getPageParams();
                    url = rdaTableColumn.getUrl();
                    previousLevel=true;
                }
            }
            materialBillAndRdaPartsRel.setPreviousLevel(previousLevel);
            materialBillAndRdaPartsRel.setPageParams(pageParams);
            materialBillAndRdaPartsRel.setUrl(url);
            materialBillAndRdaPartsRel.setRdaPart(rdaPart1);
            list.add(materialBillAndRdaPartsRel);
        }else {
            RdaPartsRel rdaPartsRel1 = rdaPartsRelMapper.selectBillByRelId(rdaPartsRel.getParentId());
            list.add(new MaterialBillAndRdaPartsRel(rdaPartsRel1));
        }
        return list;
    }

    @Override
    public void rankSort(RdaPartsRel rdaPartsRel) {
        List<RdaPartsRel> rdaPartsRels = rdaPartsRelMapper.billofMaterial(rdaPartsRel);
        for (RdaPartsRel partsRel : rdaPartsRels) {
            updateorderforupdate(partsRel.getId(),0L,"");
        }
    }

    @Override
    public void viewSort(Sharing rdaPmsassignRel) {
        String ids = rdaPmsassignRel.getIds();
        String[] split = ids.split(",");
        //目前只可以选中一个
        String s = split[0];
        Long pmsid = Long.parseLong(rdaPmsassignRel.getPmsid());
        String temp;
        RdaPartsRel rdaPartsRelT = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(s));
        temp=rdaPartsRelT.getFindnumber();
        RdaPartsRel rdaPartsRelP = rdaPartsRelMapper.selectRdaPartsRelById(pmsid);
        rdaPartsRelT.setFindnumber(rdaPartsRelP.getFindnumber());
        rdaPartsRelP.setFindnumber(temp);
        rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRelT);
        rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRelP);
    }

    @Override
    public void copyTo(Sharing rdaRestrainwbsRel) {
        String ids = rdaRestrainwbsRel.getIds();
        String[] split = ids.split(",");
        RdaPartsRel rdaPartsRel1 = new RdaPartsRel();
        rdaPartsRel1.setId(Long.parseLong(rdaRestrainwbsRel.getToid()));
        List<RdaPartsRel> rdaPartsRels = rdaPartsRelMapper.billofMaterial(rdaPartsRel1);
        for (String s : split) {
            RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(Long.parseLong(s));
            //记录变化的id
            HashMap<Long, Long> idHashMap = new HashMap<>();
            //记录leveL
            List<Long> temp = new ArrayList<>();
            for (RdaPartsRel partsRel : rdaPartsRels) {
                //直接用partsRel数据会不全
                RdaPartsRel rdaPartsRel2 = rdaPartsRelMapper.selectRdaPartsRelById(partsRel.getId());
                long idL = SnowFlakeUtils.nextId();
                idHashMap.put(partsRel.getId(),idL);
                rdaPartsRel2.setId(idL);
                rdaPartsRel2.setParentId(idHashMap.get(partsRel.getParentId())==null?rdaPartsRel.getId():idHashMap.get(partsRel.getParentId()));
                rdaPartsRel2.setCreateTime(DateUtils.getNowDate());
                temp.add(rdaPartsRel2.getLevel()-rdaPartsRel.getLevel());
                rdaPartsRel2.setLevel((rdaPartsRel2.getLevel()-temp.get(0))+1);
                rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRel2);
                updateorderforupdate(rdaPartsRel2.getParentId(),0L,"");
            }
        }

    }

    @Override
    public List<MaterialBillAndRdaPartsRel>  reverseList(Long id) {
        return referrer(id) ;
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param rdaPartsRel 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<RdaPartsRel> selectRdaPartsRelList(RdaPartsRel rdaPartsRel)
    {
        return rdaPartsRelMapper.selectRdaPartsRelList(rdaPartsRel);
    }

    @Override
    public List<RdaEco> changeControl(Long id) {
        ArrayList<RdaEco> rdaEcos = new ArrayList<>();
        //查找关系表中的物料具体id
        RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(id);
        //通过具体物料id查找所有的关系
        RdaEcoRel rdaEcoRel = new RdaEcoRel();
        rdaEcoRel.setFromid(rdaPartsRel.getFromid());
        List<RdaEcoRel> rdaEcoRels = rdaEcoRelService.selectRdaEcoRelList(rdaEcoRel);

        for (RdaEcoRel ecoRel : rdaEcoRels) {
            rdaEcos.add(rdaEcoService.selectRdaEcoById(ecoRel.getToid()));
        }
        return rdaEcos;
    }

    @Override
    public void referenceEco(Sharing rdaPmsassignRel) {
        String ids = rdaPmsassignRel.getIds();
        String[] split = ids.split(",");
        Long pmsid = Long.parseLong(rdaPmsassignRel.getPmsid());
        //通过rel找到materal的id
        RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(pmsid);
        MaterialBill materialBill = materialBillMapper.selectMaterialBillById(rdaPartsRel.getFromid());

        //查找eco
        RdaEco rdaEco = rdaEcoService.selectRdaEcoById(Long.parseLong(split[0]));
        //查找ecorel中是否已经存在这个物料
        RdaEcoRel rdaEcoRel = new RdaEcoRel();
        rdaEcoRel.setFromid(materialBill.getId());
        rdaEcoRel.setToid(rdaEco.getId());
        List<RdaEcoRel> rdaEcoRels = rdaEcoRelService.selectRdaEcoRelList(rdaEcoRel);
        if (rdaEcoRels.size()>0){
            throw new ServiceException("物料"+materialBill.getName()+"已存在"+rdaEco.getName());
        }else {
            rdaEcoRel.setId(SnowFlakeUtils.nextId());
            rdaEcoRel.setName(materialBill.getName());
            rdaEcoRel.setRevision(materialBill.getRevision());
            rdaEcoRel.setStateid(Long.parseLong(materialBill.getStateid().toString()));
            rdaEcoRel.setDescription(materialBill.getDescription());
            rdaEcoRel.setOwnerid(SecurityUtils.getUserId());
            rdaEcoRel.setFromid(materialBill.getId());
            rdaEcoRel.setFromtype(Long.parseLong(materialBill.getTypeid().toString()));
            rdaEcoRel.setToid(rdaEco.getId());
            rdaEcoRel.setTotype(rdaEco.getId());
            rdaEcoRel.setCreateTime(DateUtils.getNowDate());
            rdaEcoRel.setTypeid(rdaEcoRel.getFromtype());
            rdaEcoRelService.insertRdaEcoRel(rdaEcoRel);
        }
    }

    @Override
    public void addEcoByMaterial(RdaEcoDto rdaEcoDto) {
        RdaEco rdaEco = new RdaEco();
        BeanUtils.copyProperties(rdaEcoDto,rdaEco);
        int i = rdaEcoService.insertRdaEco(rdaEco);
        if (i>0){
            RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(rdaEcoDto.getPmsid());
            MaterialBill materialBill = materialBillService.selectMaterialBillById(rdaPartsRel.getFromid());

            Sharing rdaPmsassignRel = new Sharing();
            //物料
            rdaPmsassignRel.setIds(materialBill.getId().toString());
            //eco
            rdaPmsassignRel.setProjectid(rdaEco.getId());
            rdaEcoService.InsertExistMaterial(rdaPmsassignRel);
        }
    }

    @Override
    public void replaceEbom(ReplaceMaterialBillDTO replaceMaterialBillDTO) {
        MaterialBill materialBill = materialBillService.selectMaterialBillById(Long.parseLong(replaceMaterialBillDTO.getFromid()));
        List<RdaPartsRel> rdaPartsRels = rdaPartsRelMapper.treeByRdaPartsRels(Long.parseLong(replaceMaterialBillDTO.getToid()));
        //不使用BOM替换
        if ("1".equals(replaceMaterialBillDTO.getRestraintype())){
            for (RdaPartsRel partsRel : rdaPartsRels) {
                rdaPartsRelMapper.deleteRdaPartsRelById(partsRel.getId());
            }
            RdaPartsRel rdaPartsRelI = new RdaPartsRel();
            rdaPartsRelI.setId(SnowFlakeUtils.nextId());
            rdaPartsRelI.setRelName(rdaPartsRels.get(0).getRelName());
            rdaPartsRelI.setFromid(materialBill.getId());
            rdaPartsRelI.setFromtype(materialBill.getTypeid());
            rdaPartsRelI.setToid(rdaPartsRels.get(0).getToid());
            rdaPartsRelI.setTotype(rdaPartsRels.get(0).getTotype());
            rdaPartsRelI.setLevel(rdaPartsRels.get(0).getLevel());
            rdaPartsRelI.setParentId(rdaPartsRels.get(0).getParentId());
            rdaPartsRelI.setCreateTime(DateUtils.getNowDate());
            rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRelI);
            updateorderforupdate(rdaPartsRelI.getParentId(),0L,"");
        }else if("2".equals(replaceMaterialBillDTO.getRestraintype())){
            //替换为现有零件的BOM
            //会把零件A替换为零件B，并且零件B会克隆零件A的BOM结构
            RdaPartsRel rdaPartsRel = rdaPartsRels.get(0);
            rdaPartsRel.setFromid(materialBill.getId());
            rdaPartsRel.setFromtype(materialBill.getTypeid());
            rdaPartsRel.setQuantity(null);
            rdaPartsRel.setQuantity(null);
            rdaPartsRel.setRemark(null);
            rdaPartsRel.setCreateTime(DateUtils.getNowDate());
            rdaPartsRel.setUpdateTime(DateUtils.getNowDate());
            rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRel);
        }
    }

    @Override
    public void replacewithNewMaterialBill(MaterialBillReplaceNewDTO materialBillReplaceNewDTO) {
        MaterialBill materialBill = new MaterialBill();
        BeanUtils.copyProperties(materialBillReplaceNewDTO,materialBill);
        if ("1".equals(materialBillReplaceNewDTO.getRestraintype().toString())){
            materialBill.setId(SnowFlakeUtils.nextId());
            materialBill.setDescription(materialBillReplaceNewDTO.getRemark());
            materialBill.setParentid(null);
            materialBill.setCreateTime(DateUtils.getNowDate());
            materialBillMapper.insertMaterialBill(materialBill);
            rdaPartsRelMapper.treeByRdaPartsRels(materialBillReplaceNewDTO.getId());
        }
    }


    @Override
//    public List<Document> selectRdaPartsRelList(Long id) throws Exception {
    public List<HashMap<String, Object>> selectRdaPartsRelList(Long id) throws Exception {
        List<HashMap<String, Object>> hashMapList = new ArrayList<>();
//        List<Document> documents = new ArrayList<>();
        RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectRdaPartsRelById(id);
        Long fromid = rdaPartsRel.getFromid();
        RdaPartsRel rdaPartsRel1 = new RdaPartsRel();
        rdaPartsRel1.setFromid(fromid);
        rdaPartsRel1.setRelName("doc");
        List<RdaPartsRel> rdaPartsRels = rdaPartsRelMapper.selectRdaPartsRelList(rdaPartsRel1);
        for (RdaPartsRel partsRel : rdaPartsRels) {
//            Document document = documentService.selectDocumentById(partsRel.getToid());
            HashMap<String, Object> stringObjectHashMap = dynamicService.selectDataById(tableName, partsRel.getToid());
            // 如果stringObjectHashMap为空，则跳过当前循环，继续下一个循环
            if (stringObjectHashMap == null || stringObjectHashMap.isEmpty()) {
                continue;
            }
//            Document document = new Document();
//            Document document1 = BeanMapUtils.mapToBean(stringObjectHashMap, document.getClass());
            hashMapList.add(stringObjectHashMap);
//            documents.add(document1);
        }
//        return documents;
        return hashMapList;

    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param rdaPartsRel 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertRdaPartsRel(RdaPartsRel rdaPartsRel)
    {
        rdaPartsRel.setCreateTime(DateUtils.getNowDate());
        return rdaPartsRelMapper.insertRdaPartsRel(rdaPartsRel);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param rdaPartsRel 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateRdaPartsRel(RdaPartsRel rdaPartsRel)
    {
        rdaPartsRel.setUpdateTime(DateUtils.getNowDate());
        return rdaPartsRelMapper.updateRdaPartsRel(rdaPartsRel);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteRdaPartsRelByIds(Long[] ids)
    {
        //删除关联的表数据
        int i = rdaPartsRelMapper.deleteRdaPartsRelByIds(ids);
        if (i>0){
            rdaPartDynamicattributevalueService.deleteRdaPartDynamicattributevalueByObjectId(ids);
        }

        return i;
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteRdaPartsRelById(Long id)
    {
        return rdaPartsRelMapper.deleteRdaPartsRelById(id);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int updateorderforupdate(Long parentid,Long materialid,String parentrank) {
        //传入的父id、物料id和父级排名
        if(parentid>0){
            //先查找父id的物料信息
            RdaPartsRel rdaPartsRel = rdaPartsRelMapper.selectBillByRelId(parentid);
            if(rdaPartsRel!=null){
                //得到父级排名
                parentrank = rdaPartsRel.getFindnumber();
            }
        }
        //查找父id下的所有物料
        RdaPartsRel rdaPartsRelP = new RdaPartsRel();
        rdaPartsRelP.setParentId(parentid);
//        List<RdaPartsRel> lists = rdaPartsRelMapper.selectRdaPartsRelList(rdaPartsRelP);
        List<RdaPartsRel> list = rdaPartsRelMapper.selectRdaPartsAndBillRelList(rdaPartsRelP);

        List<RdaPartsRel> nullList=new ArrayList<>();
        int i=0;
        int num =0;
        //更新级别号开始
        for(RdaPartsRel mb:list){
            String newrank;
            //对于已有级别号为空的物料，将其添加到nullList中
            if(mb.getFindnumber()==null){
                nullList.add(mb);
            }else{
                i++;
                if(mb.getLevel()==1 || parentrank==null || "".equals(parentrank)){
                    newrank= String.valueOf(i);
                }else{
                    newrank= parentrank.trim()+"."+String.valueOf(i).trim();
                }
                if(!mb.getFindnumber().equals(newrank)){
                    RdaPartsRel newmb = new RdaPartsRel();
                    newmb.setId(mb.getId());
                    newmb.setFindnumber(newrank);
                    rdaPartsRelMapper.updateRdaPartsRel(newmb);
                    if(num>0){
                        updateorderforupdate(mb.getId(),0L,newrank);
                    }
                }
            }
        }
        if(nullList.size()>0){
            int k=i;
            for(RdaPartsRel mb1:nullList){
                k++;
                String newrank;
                if(mb1.getLevel()==1 || parentrank==null || "".equals(parentrank)){
                    newrank= String.valueOf(k);
                }else{
                    newrank= parentrank.trim()+"."+String.valueOf(k).trim();
                }
                if(mb1.getFindnumber()==null || !mb1.getFindnumber().equals(newrank)){
                    RdaPartsRel newmb1 = new RdaPartsRel();
                    newmb1.setId(mb1.getId());
                    newmb1.setFindnumber(newrank);
                    num = rdaPartsRelMapper.updateRdaPartsRel(newmb1);
                    if(num>0){
                        updateorderforupdate(mb1.getId(),0L,newrank);
                    }
                }
            }
        }
        return num;
    }
}
